import os
import subprocess
import platform
import shutil
import logging

def generate_service_file(current_dir=os.getcwd()):
    # 获取当前运行目录
    service_content = f"""[Unit]
Description=RSS Client Daemon
After=network.target

[Service]
Type=simple
WorkingDirectory={current_dir}
ExecStart=/usr/bin/python3 {current_dir}/main.py
Restart=on-failure
RestartSec=5s
User=root

[Install]
WantedBy=multi-user.target
"""
    # 生成服务文件
    service_file_path = os.path.join(current_dir, "rss_client.service")
    with open(service_file_path, "w") as service_file:
        service_file.write(service_content)
    logging.info(f"服务文件已生成: {service_file_path}")

def register_self():
    # 检测操作系统是否为 Ubuntu
    if platform.system().lower() != "linux" or "ubuntu" not in platform.version().lower():
        logging.error("当前操作系统不是 Ubuntu，程序退出。")
        exit(1)

    service_name = "rss_client.service"
    daemon_name = "RSS Client Daemon"
    # 检测 systemctl 中是否存在名为 RSS Client Daemon 的服务
    try:
        result = subprocess.run(["systemctl", "is-active", daemon_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if result.returncode == 0:
            logging.info(f"检测到服务 {daemon_name} 正在运行，正在停止并禁用...")
            subprocess.run(["systemctl", "stop", daemon_name], check=True)
            subprocess.run(["systemctl", "disable", daemon_name], check=True)
        else:
            logging.info(f"服务 {daemon_name} 未运行。")
    except Exception as e:
        logging.error(f"检测或停止服务时出错: {e}")
        exit(1)
    current_dir = os.getcwd()
    generate_service_file(current_dir)
    service_file_path = os.path.join(current_dir, service_name)
    # 检查服务文件是否存在
    if not os.path.exists(service_file_path):
        logging.error(f"服务文件 {service_file_path} 不存在，请确保文件存在后重试。")
        exit(1)

    # 复制服务文件到 systemd 目录
    target_path = f"/etc/systemd/system/{service_name}"
    try:
        shutil.copy(service_file_path, target_path)
        logging.info(f"服务文件已复制到 {target_path}。")
    except Exception as e:
        logging.error(f"复制服务文件时出错: {e}")
        exit(1)

    # 启用并启动服务
    try:
        subprocess.run(["systemctl", "daemon-reload"], check=True)
        subprocess.run(["systemctl", "enable", service_name], check=True)
        subprocess.run(["systemctl", "start", service_name], check=True)
        logging.info(f"服务 {daemon_name} 已成功启用并启动。")
    except Exception as e:
        logging.error(f"启用或启动服务时出错: {e}")
        exit(1)